import React, { useCallback, useState } from 'react';
import { connect } from 'umi';
import { departmentAPI } from '@/pages/SystemController/DepartmentController/type';
import { useDpmData, DeptContext } from './hooks';
import { SearchBox, TableList, getColumns } from './component';
import cls from 'classnames';
import { message } from 'antd';
import { CaretDownOutlined, CaretRightOutlined } from '@ant-design/icons/lib/icons';
import AddEditDeptModal from './component/operationCompon/AddEditDeptModal';
import ConfirmModal from './component/operationCompon/ConfirmModal';
import useRequest from '@ahooksjs/use-request';
import { chanageModifyState } from './service';
import { getCompanyID, getPosIDs, getUserDepID, getUserID } from '@/utils';
import DetailInfoDrawer from './component/operationCompon/DetailInfoDrawer';

import './styles.less';
import '@/common/pageLayout.less';

const Index: React.FC<departmentAPI.IpropsType> = ({ permissions }) => {
  const { run, dataSource, loading } = useDpmData(permissions);
  const viewId = 'deptAddEditModa-view-' + Math.random();
  const clsName = 'depart-layout';
  const tableListRef: any = React.useRef();
  const searchBoxRef: any = React.useRef();

  // 保存编辑时候传入的id
  const [recordEdit, setRecordEdit] = useState<any>(null);
  const [tableRowObj, setTableRowObj] = useState<any>(null);

  // 是否打开禁用提示modal
  const [openConfirm, setOpenConfirm] = useState<boolean>(false);
  const onConfirmModal = useCallback(
    (record: Record<any, any>) => {
      setTableRowObj(record);
      setOpenConfirm(true);
    },
    [openConfirm],
  );
  const closeConfirmModal = useCallback(() => {
    setOpenConfirm(false);
  }, [openConfirm]);

  // 点击查看详情
  const [isShowDetail, setIsShowDetail] = useState<boolean>(false);
  const [detailID, setDetailID] = useState<string>('');
  const onDetail = useCallback(
    (record) => {
      setIsShowDetail(true);
      setDetailID(record);
    },
    [isShowDetail],
  );
  const closeDetail = useCallback(() => {
    setIsShowDetail(false);
  }, [isShowDetail]);

  // 表格行操作
  const onOptClick: departmentAPI.IOperationClick = {
    onEdit: (record) => {
      addOrEditModal(true, record);
      tableListRef?.current?.setTableChanage(record?.id, record);
    },
    onView: (record) => {
      onDetail(record);
    },
    // 改变组织结构状态
    onIsOpen: (check, e, record) => {
      if (check) {
        if (record?.pIsOpen == 1) {
          // 启用
          chanageDeptState?.run(record, check);
        } else {
          onConfirmModal(record);
        }
      } else {
        onConfirmModal(record);
      }
    },
  };
  // 表格行操作
  const [showColumns, setShowColumns] = useState(getColumns('', permissions, onOptClick));

  // 禁用组织机构
  const chanageCloseDept = (record: Record<any, any>, isCheck: boolean) => {
    chanageDeptState?.run(record, isCheck);
  };

  // 修改组织机构状态发起请求方法
  const chanageDeptState = useRequest(
    (payload: any, openState: boolean) => {
      let params = {
        modifyerID: getUserID(),
        modifyPositionID: getPosIDs(),
        modifyDepartmentID: getUserDepID(),
        modifyCompanyID: getCompanyID(),
        versionNum: payload?.versionNum,
        id: payload?.id,
        isOpen: openState ? 1 : 0,
      };
      return chanageModifyState(params);
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        if (res && res?.msgFlag) {
          message?.success(res?.msg);
          onReload();
        } else {
          message?.error(res?.msg);
        }
      },
    },
  );

  // 点击添加和编辑的 modal
  const [deptAddEdit, setDeptAddEdit] = useState<boolean>(false);
  const openDeptAddEditModal = useCallback(() => {
    setDeptAddEdit(true);
  }, [deptAddEdit]);
  const closeDeptAddEditModal = useCallback(() => {
    setDeptAddEdit(false);
  }, [deptAddEdit]);

  // 点击添加组织机构
  const addOrEditModal = (isEdit: any, rowData: any) => {
    // isEdit 为 false 时为新增
    if (isEdit && rowData && JSON.stringify(rowData) != '{}') {
      setRecordEdit(rowData);
      openDeptAddEditModal();
    } else {
      setRecordEdit(null);
      openDeptAddEditModal();
    }
  };

  // 修改显示列
  const changeColumns = React.useCallback((columns) => {
    setShowColumns(columns);
  }, []);

  // 刷新
  const onReload = () => {
    // tableListRef?.current?.setExpandedKeys([]);
    run();
  };

  // 点击搜索后表格的交互
  const onSearch = (formValues: any) => {
    let columns = getColumns(formValues?.name, permissions, onOptClick);
    setShowColumns(columns);

    let expandKeys = getExpandkeys(formValues, dataSource);

    tableListRef?.current?.setExpandedKeys(expandKeys);
  };

  // 获取展开的id
  const getExpandkeys = (formValues: any, tableList: any[]) => {
    let data: any = [];
    const flatLoop = (array: any[]) => {
      array?.forEach((item) => {
        if (item?.children) {
          flatLoop(item?.children);
        }

        data.push(item);
      });
    };
    flatLoop(tableList);

    let searchKey = data?.filter((item: any) => {
      return item?.name?.includes(formValues?.name);
    });

    let idList: any = [];
    let transltateFn = (data: any[], pId: any, itemID: any) => {
      data.map((item) => {
        if (item?.pID) {
          if (item.id === pId) {
            idList.push(item.id);
            transltateFn(data, item.pID, item?.id);
          }
        } else if (formValues && formValues?.name) {
          idList.push(item?.id);
        }
      });
    };

    if (searchKey.length <= 0) {
      message.warn('暂未找到搜索内容');
      return [];
    }
    searchKey?.forEach((item: any) => {
      transltateFn(data, item?.pID, item?.id);
    });

    let flagArray = new Set([...idList]);

    return Array.from(flagArray);
  };

  // 修改下拉展开图标
  const expandIcon = (props: any) => {
    // let title = <span>{props.record?.name}</span>;
    // let searchData = searchBoxRef?.current?.getSearchValue()?.name ? searchBoxRef?.current?.getSearchValue()?.name : [];
    // let searchKey = searchBoxRef?.current?.getSearchValue() ? Object.keys(searchBoxRef?.current?.getSearchValue())?.[0] : '';
    // if (searchKey) {
    //   const index = props.record[searchKey] ? props.record[searchKey].indexOf(searchData) : -1;
    //   const beforeStr = props.record[searchKey] ? props.record[searchKey].substr(0, index) : '';
    //   const afterStr = props.record[searchKey] ? props.record[searchKey].substr(index + searchData?.length) : '';
    //   title = index > -1 && searchData != '' ? (
    //     <span id={props.record.id}>
    //       {beforeStr}
    //       <span style={{ color: '#f50' }}>{searchData}</span>
    //       {afterStr}
    //     </span>
    //   ) : (
    //     <span id={props.record.id}>{props.record.name}</span>
    //   );
    // }
    if (props.record.children && props.record.children.length > 0) {
      if (props.expanded) {
        return (
          <span
            onClick={(e) => {
              props.onExpand(props.record, e);
            }}
            style={{
              float: 'left',
              marginRight: '5px',
            }}
          >
            <span style={{ fontSize: '10px' }}>
              <CaretDownOutlined />
            </span>
          </span>
        );
      } else {
        return (
          <span
            onClick={(e) => {
              props.onExpand(props.record, e);
            }}
            style={{
              float: 'left',
              marginRight: '5px',
            }}
          >
            <span style={{ fontSize: '10px' }}>
              <CaretRightOutlined />
            </span>
          </span>
        );
      }
    } else {
      return (
        <span
          style={{
            float: 'left',
            marginRight: '5px',
          }}
        >
          <span style={{ fontSize: '10px', visibility: 'hidden' }}>
            <CaretRightOutlined />
          </span>
        </span>
      );
    }
  };

  // 给搜索功能 平铺树结构数据
  const tileTreeData = () => {
    let newTreeArr: any = [];
    let loop = (data: any[]) => {
      data?.forEach((item) => {
        newTreeArr.push({
          id: item?.id,
          name: item?.name,
          pID: item?.pID,
          pName: item?.pName,
          category: item?.category,
        });
        if (item?.children && item?.children?.length > 0) {
          loop(item?.children);
        }
      });
    };
    loop(dataSource);
    return newTreeArr;
  };

  // 获取最新的搜索的KEy
  const getNewKey = (key: any) => {
    let newTableRow: any = [];
    let loop = (treeData: any[]) => {
      treeData?.forEach((item) => {
        if (item && item?.children && item?.children?.length > 0) {
          loop(item?.children);
        }
        if (item?.id == key) {
          newTableRow.push(item);
        }
      });
    };
    loop(dataSource);
    tableListRef?.current?.setTableChanage(key, newTableRow);
  };

  return (
    <DeptContext.Provider
      value={{
        viewId: viewId,
        curRes: permissions,
      }}
    >
      <div className={cls(clsName)} style={{ overflow: 'hidden', height: '100%', width: '100%' }}>
        <div className={cls(`${clsName}-search`)}>
          <SearchBox
            onReload={onReload}
            showColumns={showColumns}
            changeColumns={changeColumns}
            onSearch={onSearch}
            ref={searchBoxRef}
            dataList={tileTreeData}
            getNewKey={getNewKey}
            addOrEditModal={addOrEditModal}
          />
        </div>
        <div className={cls(`${clsName}-list`)}>
          <TableList dataSource={dataSource} loading={loading} columns={showColumns} ref={tableListRef} expandIcon={expandIcon} />
        </div>
        {deptAddEdit && (
          <AddEditDeptModal
            onClose={closeDeptAddEditModal}
            visible={deptAddEdit}
            recordEdit={recordEdit}
            selectColumnKey={tableListRef?.current?.openSearchKey}
            selectColumnRow={tableListRef?.current?.openSearchRow}
            superiorDept={dataSource}
            onReload={onReload}
          />
        )}

        {openConfirm && (
          <ConfirmModal visible={openConfirm} onClose={closeConfirmModal} onReload={onReload} chanageDeptState={chanageCloseDept} tableRowObj={tableRowObj} />
        )}

        <DetailInfoDrawer visible={isShowDetail} detailID={detailID} onCloseDra={closeDetail} />
      </div>
    </DeptContext.Provider>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  permissions: baseLogin?.permissions,
  navTab,
}))(Index);
